//
//  NvProduceTemplateCollectionViewCell.m
//  NvSellerShow
//
//  Created by Meicam on 2017/2/8.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvProduceTemplateCollectionViewCell.h"
#import "Utils.h"

@implementation NvProduceTemplateCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.coverImageView.layer.borderColor = [UIColor colorWithHexRGB:@"#5BC2E5"].CGColor;
    self.coverImageView.layer.cornerRadius = 5;
}

- (void)updateSubViewWith:(AssetPackageObject *)model {
    self.object = model;
    self.label.text = model.displayName;
    
    if (model.state == NvAssetPackageStateCanUse) {
        NSData *data = [NSData dataWithContentsOfFile:[self getLocalCoverImage:[model.fileSavePath stringByAppendingPathComponent:model.uuid]]];
        [self.coverImageView setImage:[UIImage imageWithData:data]];
    } else {
        [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.imageCoverUrl] placeholderImage:[UIImage imageFromBundle:@"placeholderIcon"]];
    }
    [self setStateButtonWith:model.state];
}

- (void)setStateButtonWith:(NvAssetPackageState)state {
    if (state == NvAssetPackageStatePaiedNot) {
        [self.themeStateImage setImage:[UIImage imageFromBundle:@"buy_icon"]];
        [self.themeStateImage setHidden:NO];
    } else if (state == NvAssetPackageStateDownloadNot) {
        [self.themeStateImage setImage:[UIImage imageFromBundle:@"down_icon"]];
        [self.themeStateImage setHidden:NO];
    } else {
        [self.themeStateImage setHidden:YES];
    }
}

- (NSString *)getLocalCoverImage:(NSString *)path {
    NSString * jsonInfoPath = [path stringByAppendingString:@"/info.json"];
    if([[NSFileManager defaultManager] fileExistsAtPath:jsonInfoPath]){
        //parse info.json in assetPath
        NSData *jdata = [[NSData alloc]initWithContentsOfFile:jsonInfoPath];
        NSError *error;
        NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:jdata options:0 error:&error];
        if(error || jsonObj == nil){
            return nil;
        }
        return [path stringByAppendingPathComponent:[jsonObj objectForKey:@"cover"]];
    }
    return nil;
}

@end
